from typing import Tuple, Union

from fastapi import Request, Response

from common.route.route import CustomerBaseRoute
from common.utils.resp import JsonResponse, RC


class MallMatchAPIRoute(CustomerBaseRoute):
    """
    主要就是需要验证path中的mall code和tenant是否匹配
    """
    async def do_before(self, request: Request, *args, **kwargs) -> Tuple[bool, Union[Response, None]]:
        from common.g.g import G_TENANT_BLOOMFILTER
        from common.g.g import G_MALL_BLOOMFILTER
        from service.tenant_service import TenantMallService
        code = request.path_params.get("code")
        if code:
            tenant_id = request.state.tenant_id
            tenant_exist = await G_TENANT_BLOOMFILTER.exist(f"tenant:{tenant_id}")
            if not tenant_exist:
                return False, JsonResponse(code=RC.TENANT_NOT_EXIST, msg=f"租户:{tenant_id}不存在").to_response()
            mall_exist = await G_MALL_BLOOMFILTER.exist(code)
            if not mall_exist:
                return False, JsonResponse(code=RC.MALL_NOT_EXIST, msg=f"商城:{code}不存在").to_response()
            # todo 优化tenant和mall的关系查询

            tms = TenantMallService(request.app.mgw, request.app.redis)
            mall_info = await tms.get_mall_info_by_code(tenant_id, code)
            if not mall_info:
                response: Response = JsonResponse(code=RC.FORBIDDING, msg="mall和tenant不匹配").to_response()
                return False, response
            request.state.mall_id = mall_info.get("mall_id")
        return True, None

